package com.github.common.extend.demo.config.json.fastjson;

import com.alibaba.fastjson.serializer.PropertyFilter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * 兼容下jackson的{@link JsonIgnore}注解
 * @author wangjj7
 * @date 2024/4/2
 * @description
 */
public class IgnorePropertyFilter implements PropertyFilter {

    @Override
    public boolean apply(Object object, String name, Object value) {
        if (object == null) {
            return true;
        }
        // 获取字段上的注解
        Field field = ReflectionUtils.findField(object.getClass() ,name);
        if (field == null){
            return true;
        }
        JsonIgnore fieldAnnotation = field.getAnnotation(JsonIgnore.class);
        // 如果字段上注解了，并且值为true，表示需要过滤
        if (null != fieldAnnotation && fieldAnnotation.value()) {
            return false;
        }
        return true;
    }

}
